package cn.zhuama.org.service.impl;

import cn.zhuama.basic.exception.BusinessException;
import cn.zhuama.basic.sevice.impl.BaseServiceImpl;
import cn.zhuama.basic.util.*;
import cn.zhuama.common.domain.BinderDto;
import cn.zhuama.common.domain.LogininfoData;
import cn.zhuama.org.domain.Logininfo;
import cn.zhuama.org.domain.User;
import cn.zhuama.org.mapper.EmployeeMapper;
import cn.zhuama.org.mapper.LogininfoMapper;
import cn.zhuama.org.mapper.UserMapper;
import cn.zhuama.org.service.ILogininfoService;
import cn.zhuama.system.domain.Menu;
import cn.zhuama.user.constant.WeChatContant;
import cn.zhuama.user.domain.Wxuser;
import cn.zhuama.user.mapper.WxuserMapper;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static cn.zhuama.basic.util.JwtUtils.generateTokenExpireInSeconds;

/**
 * 业务实现类：
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {
    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    UserMapper userMapper;

    @Autowired
    LogininfoMapper logininfoMapper;

    @Autowired
    WxuserMapper wxuserMapper;

    @Autowired
    EmployeeMapper employeeMapper;
    @Override
    public AjaxResult wechatBinder(BinderDto binderDto) {
        String phone = binderDto.getPhone();
        String verifyCode = binderDto.getVerifyCode();
        String accesstoken = binderDto.getAccessToken();
        String openId = binderDto.getOpenId();
        //校验
        //1.校验 - 空置校验
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(verifyCode)){
            throw new BusinessException("数据不能为空");
        }

        //2.校验 - 验证码是否过期  //code:1215215155
        Object redisCode = redisTemplate.opsForValue().get("bind" + phone);
        if(redisCode==null){
            throw new BusinessException("验证码过期");
        }
        //3.校验 - 验证码是否正确
        if(!redisCode.toString().split(":")[0].equalsIgnoreCase(verifyCode.trim())){
            throw new BusinessException("验证码错误");
        }


        //绑定用户：t_wxUser【user_id】 绑定 t_user
        //4.获取WxUser - 发送第三个请求 - json字符串
        //nm又是这个sb路由 一会看看怎么个解决 用这个路由可以获取数据
        String url = WeChatContant.wxuserUrl
                .replace("ACCESS_TOKEN",accesstoken)
                .replace("OPENID",openId);

        String jsonStr = HttpUtil.httpGet(url);
        //通过这个申请过来的路由 获取用户信息
        Wxuser wxuser = jsonStr2Wxuser(jsonStr); //user_id

        //5.通过phone查询User
        User user = userMapper.loadByPhone(phone);
        //5.1.如果没有 - 根据phone创建User对象 - 创建Logininfo对象 - 保存Logininfo对象 - 保存User对象
        if(user == null){
            user = phone2User(phone);
            Logininfo logininfoTmp= user2Logininfo(user);

            logininfoMapper.save(logininfoTmp);
            user.setLogininfo_id(logininfoTmp.getId());
            userMapper.save(user);
        }
        //6.将User对象的id设置到WxUser对象中
        wxuser.setUser_id(user.getId());
        //正常逻辑不需要再重新给一遍
        //应该获取一份logininfoid
       // user.setLogininfo_id(user2Logininfo(user).getId());
        //7.将WxUser对象添加到数据库
        wxuserMapper.save(wxuser);
        Long ID= user.getLogininfo_id();
        //8.做免密登录
        Logininfo logininfo = logininfoMapper.queryOne(user.getLogininfo_id());
        String token = UUID.randomUUID().toString();
        //去掉密码和盐值 - 安全
        logininfo.setPassword(null);
        logininfo.setSalt(null);
        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
        Map<String, Object> map = new HashMap<>();
        map.put("token",token);
        map.put("logininfo",logininfo);

        return AjaxResult.me().setObject(map);
    }

    @Override
    public Map<String,Object> newToken(Logininfo logininfo) throws Exception {
        //在这里重新搞个 token
        //先获取一个完整的logininfo
        Logininfo logininfo1 = logininfoMapper.queryOne(logininfo.getId());
        //权限
        List<String> permissions = employeeMapper.loadPerssionSnByLogininfoId(logininfo1.getId());
        //目录 全部
        List<Menu> menus = employeeMapper.loadMenuSnByLogininfoId(logininfo1.getId());
        LogininfoData logininfoData = new LogininfoData();
//        logininfoData.setMenus(menus);
//        logininfoData.setPermission(permission);
        logininfoData.setLogininfo(logininfo);
        //这样生成的key才包含全部信息
        PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource("auth_rsa.pri").getFile());
        String token = generateTokenExpireInSeconds(logininfoData, privateKey, 3600);
        Map<String,Object> map = new HashMap<>();
        map.put("token",token);
        map.put("menus",menus);
        map.put("permissions",permissions);
        return map;

    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        return logininfo;
    }

    private User phone2User(String phone) {
            User user = new User();
            user.setUsername(phone);
            user.setPhone(phone);
            String salt = StrUtils.getComplexRandomString(32);
            //随机的纯数据密码
            String randomPwd = StrUtils.getRandomString(6);
            String md5Pwd = Md5Utils.encrypByMd5(randomPwd + salt);
            user.setSalt(salt);
            user.setPassword(md5Pwd);
            return user;
    }

    private Wxuser jsonStr2Wxuser(String jsonStr) {
        Wxuser wxuser = new Wxuser();
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        wxuser.setOpenid(jsonObject.getString("openid"));
        wxuser.setNickname(jsonObject.getString("nickname"));
        wxuser.setSex(jsonObject.getInteger("sex"));
        wxuser.setAddress(jsonObject.getString("country") + jsonObject.getString("province") + jsonObject.getString("city"));
        wxuser.setHeadimgurl(jsonObject.getString("headimgurl"));
        wxuser.setUnionid(jsonObject.getString("unionid"));
        return wxuser;
    }
}
